package org.leumasjaffe.initiativeTracker.distributed.controller;

import static org.leumasjaffe.initiativeTracker.operator.InitiativeController.tracker;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.leumasjaffe.initiativeTracker.operator.CharacterLinker;
import org.leumasjaffe.initiativeTracker.operator.InitiativeController;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.wpi.heineman.xml.Message;
import edu.wpi.heineman.client.IMessageHandler;

@NonNullByDefault
public class DamageHandler implements IMessageHandler {

	@Override
	public void process(Message response) {
		Node node = response.contents.getFirstChild();
		NodeList nl = node.getChildNodes();
		NamedNodeMap map = node.getAttributes();

		@SuppressWarnings("null")
		InitiativeController tracker = tracker(map.getNamedItem("game").getNodeValue());
		
		int count = 0;
		for (int i = 0; i < nl.getLength(); i++) {
			NamedNodeMap mapi = nl.item(0).getAttributes();
			
			int id = Integer.decode(mapi.getNamedItem("id").getNodeValue());
			int dmg = Integer.decode(mapi.getNamedItem("value").getNodeValue());
			Node tempNode = mapi.getNamedItem("temp");
			boolean temp = false;
			if (tempNode != null)
				temp = Boolean.parseBoolean(tempNode.getNodeValue());

			CharacterLinker cl = tracker.list.lookup(id);
			/*if (cl == null)
				System.err.println("Character referenced by id=" + id + " does not exist anymore");
			else/**/ if (cl.damage(dmg, temp)); {
				count++;
				tracker.root.addDeath(i-count);
			}
		}
		tracker.root.rebuild();
	}

	@Override
	public IMessageHandler newCopy() {
		return new DamageHandler();
	}

}
